<template>
  <el-dialog v-model="open" :show-close="false" :title="title" @open="initOpen" custom-class="building-dialog"
    destroy-on-close width="1200px" @close="close">
    <el-scrollbar>
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px" v-loading="formLoading"
        :scroll-to-error="true">
        <el-space direction="vertical">
          <div shadow="never" class="assess">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="任务编号：" prop="assessCode">
                  <el-input v-model="form.assessCode" clearable :disabled="!!form.id"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="任务名称：" prop="assessName">
                  <el-input v-model="form.assessName" clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="border-bottom">
              <el-col :span="24">
                <el-form-item label="任务描述：" prop="assessDesc">
                  <el-input v-model="form.assessDesc" type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" resize="none"
                    clearable></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="border-bottom">
              <el-form-item label="选择房屋基础数据" style="display:block;width: 100%;" prop="houseDataFlag">
                <el-col :span="24">
                  <el-row justify="space-between">
                    <el-radio-group v-model="form.houseDataFlag" @change="houseDataChange" class="column">
                      <el-radio v-for="item in houseBasicData" :key="item.value" :label="item.value" size="large">
                        <el-space>
                          {{ item.name }}
                          <el-form-item prop="houseData" v-show="form.houseDataFlag == item.value"
                            style="margin: 0!important">
                            <el-input v-model="form.houseData" style="width: 300px;"></el-input>
                          </el-form-item>
                          <el-button plain @click="chooseDataSource('houseData', item.name, form.houseData)"
                            v-show="form.houseDataFlag == item.value">选择数据版本</el-button>
                        </el-space>
                      </el-radio>
                    </el-radio-group>
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row class="border-bottom" v-if="!isDisabled">
              <el-form-item label="确定评估区域" style="display:block;width: 100%;" prop="radio2">
                <el-col :span="24">
                  <el-row justify="space-between">
                    <el-space alignment="start">
                      <el-radio-group v-model="form.radio2" class="column" @change="radio2Change">
                        <el-radio label="0" size="large">
                          <el-space>
                            <span>按省市区县</span>
                            <el-form-item prop="list" v-if="form.radio2 == '0'" style="margin: 0!important">
                              <AreaCascader :checkedData="form.list" @getAreaValue="getAreaValue" style="width: 300px" />
                            </el-form-item>
                          </el-space>
                        </el-radio>
                        <el-radio label="1" size="large">
                          <el-space>
                            <span>地图圈定区域</span>
                            <el-radio-group v-model="form.radio22" style="flex-wrap: nowrap;margin-left: 100px;"
                              v-if="form.radio2 == '1'" @change="radio22Change">
                              <el-radio label="1">
                                <el-form-item prop="coordinateRange" v-if="form.radio22 == '1'">
                                  <el-space>地图划定区域
                                    <svg-icon icon-class="map" style="width: 25px;height: 25px"
                                      @click="goToMap"></svg-icon>
                                  </el-space>
                                </el-form-item>
                                <span v-else>地图划定区域</span>
                              </el-radio>
                              <el-radio label="2">
                                <el-space>通过输入经纬度范围
                                  <el-form-item prop="areaRange" v-if="form.radio22 == '2'">
                                    <el-input style="width: 200px" v-model="form.areaRange"></el-input>
                                  </el-form-item>
                                </el-space>
                              </el-radio>
                            </el-radio-group>
                          </el-space>
                        </el-radio>
                      </el-radio-group>
                    </el-space>
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row class="border-bottom">
              <el-form-item label="评估方法" style="display:block;width: 100%;" prop="assessType">
                <el-col :span="24">
                  <el-row justify="space-between">
                    <el-radio-group v-model="form.assessType" @change="assessTypeChange">
                      <el-radio v-for="item in assessType" :label="item.value" :disabled="isDisabled">{{ item.name }}</el-radio>
                    </el-radio-group>
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row class="border-bottom">
              <el-form-item label="评估内容" style="display:block;width: 100%;" prop="assessObj">
                <el-col :span="24">
                  <el-row justify="space-between">
                    <el-checkbox-group v-model="form.assessObj" class="column" @change="assessObjChange">
                      <el-checkbox v-for="item in isDisabled?assessObj.filter(val=>val.value=='0'):assessObj" :label="item.value" :disabled="item.value == '0'"
                        size="large">
                        <el-row align="middle" style="padding: 0">
                          <span>{{ item.name }}</span>
                          <el-space v-if="item.value == '1'" @click.prevent="" style="width: auto;padding: 0 10px;">
                            <el-form-item prop="popluationVersion" style="margin: 0!important">
                              <el-input v-model="form.popluationVersion" readonly style="width: 300px"
                                :disabled="!form.assessObj.includes('1')"></el-input>
                            </el-form-item>
                            <el-button plain :disabled="!form.assessObj.includes('1')"
                              @click.prevent="chooseCasualtiesData('popluationVersion')">人口数据版本</el-button>
                          </el-space>
                          <el-space v-if="item.value == '2'" @click.prevent="" style="width: auto;padding: 0 10px;">
                            <el-form-item prop="gdpVersion" style="margin: 0!important">
                              <el-input v-model="form.gdpVersion" readonly style="width: 300px"
                                :disabled="!form.assessObj.includes('2')"></el-input>
                            </el-form-item>
                            <el-button plain :disabled="!form.assessObj.includes('2')"
                              @click.prevent="chooseCasualtiesData('gdpVersion')">经济数据版本</el-button>
                          </el-space>
                        </el-row>
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row class="border-bottom" v-if="form.assessType == '0'">
              <el-form-item label="危险性数据" style="display:block;width: 100%;" prop="seismicInputMode">
                <el-col :span="24">
                  <el-row justify="space-between">
                    <el-checkbox-group v-model="form.seismicInputMode" class="column" @change="seismicInputModeChange">
                      <el-checkbox label="0" size="large">
                        <el-space>
                          <span>设定烈度（VI、VII、VIII、IX、X）</span>
                        </el-space>
                      </el-checkbox>
                      <el-checkbox label="1" size="large">
                        <el-row align="middle" style="padding: 0">
                          <span>超越概率</span>
                          <el-space @click.prevent="" style="width: auto;padding: 0 10px;">
                            <el-form-item prop="fourProbabilisticVersions" style="margin: 0!important">
                              <el-input v-model="form.fourProbabilisticVersions" style="width: 300px;"
                                :disabled="!form.seismicInputMode.includes('1')"></el-input>
                            </el-form-item>
                            <el-button plain
                              @click="chooseDataSource('fourProbabilisticVersions', '超越概率', form.fourProbabilisticVersions)"
                              :disabled="!form.seismicInputMode.includes('1')">选择数据</el-button>
                          </el-space>
                          <el-radio-group v-model="form.ldPga" style="width: 200px"
                            :disabled="!form.seismicInputMode.includes('1')">
                            <el-radio label="0">烈度</el-radio>
                            <el-radio label="1">PGA</el-radio>
                          </el-radio-group>
                        </el-row>
                      </el-checkbox>
                      <el-checkbox label="2" size="large">
                        <el-row align="middle" style="padding: 0">
                          <span style="padding-right: 1em">地震影响场</span>
                          <el-space @click.prevent="" style="width: auto;padding: 0 10px;">
                            <el-form-item prop="influenceFieldVersion" style="margin: 0!important">
                              <el-input v-model="form.influenceFieldVersion" style="width: 300px;" readonly
                                :disabled="!form.seismicInputMode.includes('2')"></el-input>
                            </el-form-item>
                            <el-button plain @click="chooseInfluenceField"
                              :disabled="!form.seismicInputMode.includes('2')">选择数据</el-button>
                          </el-space>
                        </el-row>
                      </el-checkbox>
                    </el-checkbox-group>
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row class="border-bottom" v-if="form.assessType == '1'">
              <el-form-item label="危险性数据" style="display:block;width: 100%;" prop="seismicInputMode">
                <el-col :span="24">
                  <el-row justify="space-between">
                    <el-col v-if="!isDisabled">
                      <el-radio-group v-model="form.ldPga" style="width: 200px" @change="ldPgaChange">
                        <el-radio label="0">烈度</el-radio>
                        <el-radio label="1">PGA</el-radio>
                      </el-radio-group>
                      <el-radio-group v-model="form.seismicInputMode" class="column"
                        @change="seismicInputModeProbabilityChange">
                        <el-radio label="3" size="large">
                          <el-space>
                            <span>发生概率</span>
                            <el-radio-group v-model="form.occurrenceProbabilityVersion" style="flex-wrap: nowrap;"
                              :disabled="form.seismicInputMode != '3'">
                              <el-radio label="0">国家级数据</el-radio>
                              <el-radio label="1">自定义数据</el-radio>
                            </el-radio-group>
                          </el-space>
                        </el-radio>
                        <!-- <el-radio label="4" size="large">
                          <el-space>
                            <span>超越概率地震危险性</span>
                            <el-form-item prop="beyondProbabilisticVersion" style="margin: 0!important">
                              <el-input v-model="form.beyondProbabilisticVersion" style="width: 300px;"
                                :disabled="form.seismicInputMode != '4'"></el-input>
                            </el-form-item>
                            <el-button plain @click="chooseDataSource('beyondProbabilisticVersion', '超越概率地震危险性')"
                              :disabled="form.seismicInputMode != '4'">选择数据</el-button>
                          </el-space>
                        </el-radio> -->
                      </el-radio-group>
                    </el-col>
                    <el-col justify="space-between" v-else>
                      <span>发生概率（PGA）</span>
                      <br>
                      <el-radio-group v-model="form.occurrenceProbabilityVersion" style="flex-wrap: nowrap;">
                        <el-radio label="0">公里格网</el-radio>
                        <el-radio label="1">点数据</el-radio>
                      </el-radio-group>
                    </el-col>
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row>
            <el-row :class="{ 'border-bottom': form.assessType == '1' }" v-if="!isDisabled">
              <el-form-item label="易损性数据" prop="ysxVersion" style="display:block;width: 100%;" label-width="0">
                <el-col :span="24">
                  <el-row>
                    <!-- <el-space style="width: auto;"> -->
                    <span v-if="form.assessType == '0' || form.ldPga == '0'" style="width: 115px;">选择易损性矩阵：</span>
                    <span v-else style="width: 115px;">选择易损性曲线：</span>
                    <el-radio-group v-model="form.ysxVersion">
                      <el-radio label="0">国家级数据</el-radio>
                      <el-radio label="1">自定义类-完全版</el-radio>
                      <el-radio label="2">自定义类群体版</el-radio>
                      <el-radio label="3">自定义类-国家级数据生成版</el-radio>
                    </el-radio-group>
                    <!-- </el-space> -->
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row>
            <!-- T年改动较大，需求不定，注释保留 -->
            <!-- <el-row>
              <el-form-item label="T年" style="display:block;width: 100%;" label-width="0" v-if="form.assessType == '1'">
                <el-col :span="24">
                  <el-row justify="space-between">
                    <el-col :span="24">填写说明，只能填写整数，第一个必须填写1并且不能修改，后面四个按实际计算填写，比如依次填写5、30、50、100</el-col>
                    <el-col :span="10">
                      <el-space>
                        <el-input v-model.number="form.tYear1" readonly></el-input>
                        <el-input v-model.number="form.tYear2"
                          onkeyup="this.value=this.value.replace(/[^0-9]/g,'')"></el-input>
                        <el-input v-model.number="form.tYear3"
                          onkeyup="this.value=this.value.replace(/[^0-9]/g,'')"></el-input>
                        <el-input v-model.number="form.tYear4"
                          onkeyup="this.value=this.value.replace(/[^0-9]/g,'')"></el-input>
                        <el-input v-model.number="form.tYear5"
                          onkeyup="this.value=this.value.replace(/[^0-9]/g,'')"></el-input>
                      </el-space>
                    </el-col>
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row> -->
            <!-- <el-row>
              <el-form-item style="display:block;width: 100%;" label-width="0" v-if="form.assessType == '1'">
                <template #label>
                  <span>T年：</span>
                  <span style="font-weight: normal;margin-left: 10px;">{{form.year}}年</span>
                </template>
                <el-col :span="24">
                  <el-row justify="space-between">
                    <el-col :span="24">注：显示地震输入方式中，选择的危险性数据对应的的年度</el-col>
                  </el-row>
                </el-col>
              </el-form-item>
            </el-row> -->
          </div>
        </el-space>
      </el-form>
      <el-progress striped striped-flow :percentage="percent" :stroke-width="15" :text-inside="true"
        v-show="saveFlag == false" />
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="saveAssessRecord" :disabled="saveFlag == false" auto-insert-space>保存</el-button>
        <el-button plain @click="close" auto-insert-space>取消</el-button>
      </div>
    </template>
  </el-dialog>
  <el-dialog v-model="dialogVisible" title="地图划定区域" width="50%">
    <delimitMap :dialogVisible="dialogVisible" @getPolygonGeom="getPolygonGeom" />
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false" auto-insert-space>确定</el-button>
        <el-button plain @click="dialogVisible = false" auto-insert-space>取消</el-button>
      </span>
    </template>
  </el-dialog>
  <!-- 选择数据源 -->
  <!-- /buildingGridDataVersion/page -->
  <DataSource v-model:open="dataSourceOpen" :selected="dataSelect" :title="dataSourceTitle" :ldPga="form.ldPga"
    @getVersionCode="getVersionCode" :houseDataFlag="form.houseDataFlag" :type="dataVersionType" />
  <!-- 地震影响成seismicImpactField/getAll -->
  <InfluenceField v-model:open="influenceFieldOpen" :selected="form.influenceFieldVersion" @getInfluence="getInfluence" />
  <!-- 人员伤亡、经济损失数据版本 -->
  <CasualtiesData v-model:open="casualtiesOpen" :selected="form[assessObjDataType]" :type="assessObjDataType"
    @getVersionCode="getCasualtiesCode" />
  <!-- 易损性数据 -->
  <!-- <VulnerabilityData v-model:open="vulnerabilityOpen" :selected="form.ysxVersion" @getVersionCode="getVulnerability" /> -->
</template>
<script setup>
import AreaCascader from '@/views/building/components/areaCascader.vue'
import delimitMap from '@/map/building/delimitMap.vue'
import { addTask, upDateTasks, getProgress, findById, getYear } from '@/api/building/taskManage'
import DataSource from '@/views/building/components/dataSource.vue'
import InfluenceField from '@/views/building/components/influenceField.vue'
import { houseBasicData, assessType, assessObj } from '@/views/building/index'
import CasualtiesData from '@/views/building/components/casualtiesData.vue'
// import VulnerabilityData from '@/views/building/components/vulnerabilityData.vue'

const props = defineProps({
  open: Boolean,
  url: String,
  type: String,
  dictDefault: {
    type: Object,
    default: () => ({})
  }
})
const emits = defineEmits(['update:open'])
const { proxy } = getCurrentInstance()
const dialogVisible = ref(false)
const initForm = () => ({
  radio2: '0',
  houseDataFlag: '1',
  seismicInputMode: [], // 危险性数据-确定
  assessType: '0',
  assessObj: ['0'],
  list: [], // 省市区
  tYear1: '1',
  areaRange: '',
  ysxVersion: '0'
})
const form = ref(initForm())
const title = computed(() => form.value.id ? '修改任务' : '新建任务')
const tYear = computed(() => {
  let year = [form.value.tYear1, form.value.tYear2, form.value.tYear3, form.value.tYear4, form.value.tYear5].filter(item => item)
  return year.join(',')
})
const listRequired = (rule, value, cb) => {
  if (form.value.radio2 == '0') {
    if (form.value.list?.length == 0) {
      cb(new Error(rule.message))
    } else {
      cb()
    }
  } else {
    cb()
  }
}
const houseDataRequired = (rule, value, cb) => {
  if (form.value[rule.field]) {
    cb()
  } else {
    cb(new Error(rule.message))
  }
}
const paramsRequired = (rule, value, cb) => {
  if (form.value[rule.params].includes(rule.paramsValue)) {
    if (form.value[rule.field]) {
      cb()
    } else {
      cb(new Error(rule.message))
    }
  } else {
    cb()
  }
}
const rules = {
  assessCode: [{ required: true, message: '请填写任务编号！', trigger: 'blur' }],
  assessName: [{ required: true, message: '请填写任务名称！', trigger: 'blur' }],
  assessDesc: [{ required: true, message: '请填写任务描述！', trigger: 'blur' }],
  radio2: [{ required: true, message: '请选择确定评估区域！', trigger: 'change' }],
  coordinateRange: [{ required: true, message: '请选择地图划定区域！', trigger: 'change' }],
  areaRange: [{ required: true, message: '请填写经纬度范围！', trigger: 'blur' }],
  list: [{ validator: listRequired, message: '请选择省市区县！', trigger: 'change' }],
  houseData: [{ validator: houseDataRequired, message: '请选择房屋基础数据版本！', trigger: 'change' }],
  assessType: [{ required: true, message: '请选择评估方法！', trigger: 'change' }],
  assessObj: [{ required: true, message: '请选择评估内容！', trigger: 'change' }],
  popluationVersion: [{ validator: paramsRequired, message: '请选择人口数据！', trigger: 'change', params: 'assessObj', paramsValue: '1' }],
  gdpVersion: [{ validator: paramsRequired, message: '请选择经济数据！', trigger: 'change', params: 'assessObj', paramsValue: '2' }],
  seismicInputMode: [{ required: true, message: '请选择危险性数据！', trigger: 'change' }],
  fourProbabilisticVersions: [{ validator: paramsRequired, message: '请选择超越概率数据版本！', trigger: 'change', params: 'seismicInputMode', paramsValue: '1' }],
  influenceFieldVersion: [{ validator: paramsRequired, message: '请选择地震影响场数据版本！', trigger: 'change', params: 'seismicInputMode', paramsValue: '2' }],
  occurrenceProbabilityVersion: [{ validator: paramsRequired, message: '请选择发生概率版本 ', trigger: 'change', params: 'seismicInputMode', paramsValue: '3' }],
  beyondProbabilisticVersion: [{ validator: paramsRequired, message: '请选择超越概率地震危险性数据版本！', trigger: 'change', params: 'seismicInputMode', paramsValue: '4' }],
  ysxVersion: [{ required: true, message: '请选择易损性数据版本！', trigger: 'change' }]
}

const formLoading = ref(false)
const radio2Change = val => {
  if (val == '1') {
    form.value.radio22 = '1'
  }
}
const radio22Change = val => {
  if (val == '1') {
    proxy.$refs.formRef.clearValidate('areaRange')
  } else if (val == '2') {
    proxy.$refs.formRef.clearValidate('coordinateRange')
  }
}
const getPolygonGeom = (geom) => {
  form.value.coordinateRange = geom
  dialogVisible.value = false
  proxy.$refs.formRef.clearValidate('coordinateRange')
}
// 省市区县
const getAreaValue = (value) => {
  // form.value.list = value.filter(item => item.id)
  form.value.list = value
  proxy.$refs['formRef'].clearValidate('list')
}

const initOpen = () => {

}

// 查询详情
proxy.$Bus.on('getDetail', (params) => {
  const { id } = params
  formLoading.value = true
  findById({ id }).then(res => {
    let data = res.data
    form.value = data
    form.value.assessObj = data.assessObj.split(',')
    if (data.assessType == '0') {
      form.value.seismicInputMode = data.seismicInputMode.split(',')
    } else {
      form.value.year?.split(',').map((item, index) => {
        form.value[`tYear${index + 1}`] = item
      })
    }
    if(data.areaRange) {
      form.value.radio22 = '2'
    }else if(data.coordinateRange) {
      form.value.radio22 = '1'
    }
    formLoading.value = false
  })
})

proxy.$Bus.on('clearForm', () => {
  proxy.resetAllForm(form.value, initForm())
})

// 评估方法切换
const assessTypeChange = val => {
  form.value.seismicInputMode = val == '0' ? [] : '3'
  form.value.ldPga = '0'
  form.value.ysxVersion = '0'
  if (val == '1') {
    if (form.value.radio2 == '0') {
      proxy.$refs['formRef'].validateField('list', (valid) => {
        if (!valid) {
          form.value.assessType = '0'
        } else {
          form.value.occurrenceProbabilityVersion = '0'
        }
      })
    } else {
      proxy.$refs['formRef'].validateField('coordinateRange', (valid) => {
        if (!valid) {
          form.value.assessType = '0'
        } else {
          form.value.occurrenceProbabilityVersion = '0'
        }
      })
    }
  }
}
const getYearValue = () => {
  const { occurrenceProbabilityVersion, ldPga, radio2, list, coordinateRange } = form.value
  getYear({ occurrenceProbabilityVersion, ldPga, radio2, list: list || '', coordinateRange: coordinateRange || '' }).then(res => {
    form.value.year = res.data
  })
}
watchEffect(() => {
  const { assessType, occurrenceProbabilityVersion, ldPga, radio2, list, coordinateRange } = form.value
  if (assessType == '1') {
    if (occurrenceProbabilityVersion && ldPga && radio2) {
      if ((radio2 == '0' && list.length > 0) || (radio2 == '1' && coordinateRange)) {
        // getYearValue()
      }
    }
  }
})
// 评估内容切换
const assessObjChange = val => {
  if (!val.includes('1')) {
    form.value.popluationVersion = ''
  }
}

// 危险性数据切换
const seismicInputModeChange = val => {
  if(val.length > 0 && val[val.length-1] == '1') {
    form.value.ldPga = '0'
  }
  if (!val.includes('1')) {
    form.value.ldPga = ''
    proxy.$refs.formRef.clearValidate('fourProbabilisticVersions')
  }
  if (val.includes('2')) {
    // proxy.$refs.formRef.validateField('influenceFieldVersion')
  } else {
    proxy.$refs.formRef.clearValidate('influenceFieldVersion')
  }
  console.log(val, form.value)
}
const ldPgaChange = () => {
  form.value.seismicInputMode = '3'
  form.value.occurrenceProbabilityVersion = '0'
  form.value.beyondProbabilisticVersion = ''
  form.value.ysxVersion = '0'
}
const seismicInputModeProbabilityChange = val => {
  console.log(val,val.includes('3'),'====');
  if (val.includes('3')) {
  
    // proxy.$refs.formRef.validateField('occurrenceProbabilityVersion')
  } else {
    proxy.$refs.formRef.clearValidate('occurrenceProbabilityVersion')
  }
  if (val.includes('4')) {
    // proxy.$refs.formRef.validateField('beyondProbabilisticVersion')
  } else {
    proxy.$refs.formRef.clearValidate('beyondProbabilisticVersion')
  }
}

// 选择房屋基础数据
const houseDataChange = () => {
  form.value.houseData = ''
}
// 选择数据版本（房屋单体、房屋网格、四个概率、发生概率、超越概率）
const dataVersionType = ref('')
const dataSourceTitle = ref('')
const dataSourceOpen = ref(false)
const dataSelect = ref('')
const chooseDataSource = (type, title, value) => {
  dataSourceOpen.value = true
  dataVersionType.value = type
  dataSourceTitle.value = title
  dataSelect.value = value
}
const getVersionCode = val => {
  form.value[dataVersionType.value] = val
}

// 选择人口、经济数据版本
const casualtiesOpen = ref(false)
const assessObjDataType = ref('popluationVersion')
const chooseCasualtiesData = (type) => {
  casualtiesOpen.value = true
  assessObjDataType.value = type
}
const getCasualtiesCode = val => {
  form.value[assessObjDataType.value] = val
}

// 选择影响场数据
const influenceFieldOpen = ref(false)
const chooseInfluenceField = () => {
  influenceFieldOpen.value = true
}
const getInfluence = val => {
  form.value.influenceFieldVersion = val
}

// 选择易损性数据
// const vulnerabilityOpen = ref(false)
// const chooseVulnerability = () => {
//   vulnerabilityOpen.value = true
// }
// const getVulnerability = val => {
//   form.value.ysxVersion = val
// }

// 保存
let saveFlag = ref(null)
const loading = ref(null)
let cancelFunc = {}
const saveAssessRecord = () => {
  if (typeof cancelFunc.c == 'function') {
    // cancelFunc.c('取消成功！')
  }
  proxy.$refs['formRef'].validate((valid) => {
    if (valid) {
      saveFlag.value = false
      formLoading.value = true
      let data = {
        ...form.value,
        assessObj: form.value.assessObj.join(','),
        seismicInputMode: form.value.assessType == '0' ? form.value.seismicInputMode.join(',') : form.value.seismicInputMode,
        year: tYear.value,
        radio2:isDisabled.value?'':form.value.radio2
      }
      if (form.value.id) {
        // 修改后计算结果被清空，是否进行修改。继续修改清空计算数据，否退出不修改
        proxy.$modal.confirm('修改后计算结果被清空，是否进行修改？').then(() => {
          upDateTasks(data, cancelFunc).then(res => {
            if (res.code == 200) {
              saveFlag.value = true
              percent.value = 100
              cancelFunc.c = null
            }
          }).catch(err => {
            if (err.message != '取消成功') {
              cancelFunc.c = null
            }
            formLoading.value = false
          })
          getProgressData()
        }).catch(() => {
          formLoading.value = false
          close()
        })
      } else {
        addTask(data, cancelFunc).then(res => {
          if (res.code == 200) {
            saveFlag.value = true
            percent.value = 100
            cancelFunc.c = null
          }
        }).catch(err => {
          if (err.message != '取消成功') {
            cancelFunc.c = null
          }
          formLoading.value = false
        })
        getProgressData()
      }
    }
  })
}
// 进度条
let percent = ref(0)
let percentTimer = ref(null)
const getProgressData = () => {
  if (percent.value >= 100) {
    clearInterval(percentTimer.value)
  }
  percentTimer.value = setInterval(() => {
    getProgress().then(res => {
      if (percent.value <= res.data) {
        percent.value = Number(res.data)
      }
    })
  }, 1000);
}

watch([() => percent.value, () => saveFlag.value], () => {
  if (percent.value == 100 && saveFlag.value) {
    proxy.$modal.msgSuccess(form.value.id ? '修改成功！' : '保存成功！')
    formLoading.value = false
    proxy.$Bus.emit('update-list')
    close()
  }
})
const isDisabled = ref(false)
watch(() => form.value.houseDataFlag, async () => {
  if(form.value.houseDataFlag&&form.value.houseDataFlag=='0'){
    isDisabled.value = true
    form.value.assessType = '1'
    form.value.assessObj = ['0']
    form.value.ldPga = '1'
    form.value.seismicInputMode = '3'
    form.value.occurrenceProbabilityVersion = '0'
  }else{
    isDisabled.value = false
  }
}, { immediate: true, deep: true })

// 关闭
const close = () => {
  if (typeof cancelFunc.c === "function") {
    cancelFunc.c('取消成功')
  }
  saveFlag.value = null
  emits('update:open', false)
  percent.value = 0
  clearInterval(percentTimer.value)
}

// 地图划定区域
const goToMap = () => {
  dialogVisible.value = true
}

onBeforeUnmount(() => {
  proxy.$Bus.all.clear()
})
</script>

<style lang="scss" scoped>
.el-form-item.el-form-item--default {
  margin: 18px 0;
}

:deep(.el-space) {
  width: 100%;

  &>.el-space__item {
    width: 100%;
  }
}

.assess {
  border-radius: 4px;
  border: 1px solid #e4e7ed;

  // :deep(.el-card__body) {
  //   padding: 0 !important;
  // }

  .border-bottom {
    border-bottom: 1px solid var(--el-border-color-light);
    ;
  }

  .el-row {
    padding: 0 20px;
  }

  .title {
    font-weight: bold;
  }

  :deep(.column.el-checkbox-group) {
    display: flex;
    flex-direction: column;
    align-items: start;

    &>.el-checkbox {
      &>.el-checkbox__label {
        &>.el-space {
          &>.el-space__item:first-of-type {
            margin-right: 35px !important;
          }
        }
      }
    }

    .el-checkbox.el-checkbox--large {
      height: auto;
      margin: 9px 0;
    }
  }

  :deep(.column.el-radio-group) {
    display: flex;
    flex-direction: column;
    align-items: start;

    .el-radio.el-radio--large {
      height: auto;
      margin: 9px 0;
    }
  }
}
</style>
<style lang="scss">
.building-dialog {
  height: 85%;
  overflow: hidden;

  &>.el-dialog__body {
    height: calc(100% - 126px);
    overflow-y: auto;
    padding: 0;

    .el-scrollbar__view {
      padding: 20px;
    }
  }
}
</style>